package com.xmtlxx.web.controller.center.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.xmtlxx.tms.domain.*;
import com.xmtlxx.tms.domain.vo.*;
import com.xmtlxx.tms.mapper.*;
import com.xmtlxx.web.controller.center.service.ICenterService;
import com.xmtlxx.web.controller.center.service.ICommonService;
import com.xmtlxx.web.controller.center.vo.SendTaskVo;
import com.xmtlxx.web.controller.oms.service.ITaskService;
import com.xmtlxx.web.controller.tms.service.IOrderService;
import com.xmtlxx.web.controller.tms.service.IWaybillService;
import com.xmtlxx.web.controller.wms.service.IExWarehouseService;
import com.xmtlxx.web.controller.wms.service.IWarehouseService;
import com.xmtlxx.tms.domain.bo.CarrierBo;
import com.xmtlxx.tms.domain.bo.OrderBo;
import com.xmtlxx.tms.domain.bo.WaybillBo;
import com.xmtlxx.wms.domain.*;
import com.xmtlxx.wms.domain.bo.DealDtlBo;
import com.xmtlxx.wms.domain.bo.ExWarehouseBo;
import com.xmtlxx.wms.domain.bo.ViewingBo;
import com.xmtlxx.wms.domain.bo.WarehouseBo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.domain.entity.SysDept;
import com.xmtlxx.common.enums.PropertyLogType;
import com.xmtlxx.common.exception.ServiceException;
import com.xmtlxx.common.helper.LoginHelper;
import com.xmtlxx.common.utils.StringUtils;
import com.xmtlxx.oms.domain.Task;
import com.xmtlxx.oms.domain.bo.StagingBo;
import com.xmtlxx.oms.domain.bo.TaskBo;
import com.xmtlxx.oms.domain.bo.TaskDtlBo;
import com.xmtlxx.oms.domain.vo.StagingVo;
import com.xmtlxx.oms.domain.vo.TaskDtlVo;
import com.xmtlxx.oms.domain.vo.TaskVo;
import com.xmtlxx.oms.mapper.StagingMapper;
import com.xmtlxx.oms.service.ITaskDtlService;
import com.xmtlxx.system.service.ISysDeptService;
import com.xmtlxx.system.service.ISysUserService;
import com.xmtlxx.tms.service.ICarService;
import com.xmtlxx.tms.service.ICarrierService;
import com.xmtlxx.tms.service.IClientService;
import com.xmtlxx.wms.domain.vo.*;
import com.xmtlxx.wms.mapper.*;
import com.xmtlxx.wms.service.IStoreService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Service
public class CenterServiceImpl implements ICenterService {

    private final ITaskService taskService;

    private final ITaskDtlService taskDtlService;

    private final IWarehouseService warehouseService;

    private final IExWarehouseService exWarehouseService;

    private final IOrderService orderService;

    private final IWaybillService waybillService;

    private final IStoreService storeService;

    private final IClientService clientService;

    private final ICarService carService;

    private final ISysUserService userService;

    private final ICarrierService carrierService;

    private final ICommonService commonService;

    private final ISysDeptService deptService;

    private final WarehouseMapper warehouseMapper;

    private final WarehouseDtlMapper warehouseDtlMapper;

    private final ExWarehouseMapper exWarehouseMapper;

    private final ExWarehouseDtlMapper exWarehouseDtlMapper;

    private final OrderMapper orderMapper;

    private final OrderDtlMapper orderDtlMapper;

    private final OrderLogMapper orderLogMapper;

    private final WaybillMapper waybillMapper;

    private final WaybillDtlMapper waybillDtlMapper;

    private final WaybillLogMapper waybillLogMapper;

    private final ViewingMapper viewingMapper;

    private final StagingMapper stagingMapper;

    private final DealDtlMapper dealDtlMapper;

    private final PutTaskMapper putTaskMapper;

    private final PutDtlMapper putDtlMapper;

    private final PickMapper pickMapper;

    private final PickDtlMapper pickDtlMapper;

    private final InventoryMapper inventoryMapper;

    private final DealMapper dealMapper;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendsTask(SendTaskVo vo) {
        if(vo.getIds() == null || vo.getIds().length == 0){
            throw new ServiceException("参数异常，请联系管理员！");
        }
        StoreVo store = null;

        //忽略参数
        String[] ignoreProperties = {"id","createBy","createTime","updateBy","updateTime","items"};
        String[] updateIgnore = {"createBy","createTime","updateBy","updateTime","items"};
        for (String id :vo.getIds()){

            String objid = null;
            Warehouse warehouse = null;
            ExWarehouse exWarehouse = null;
            Deal deal = null;
            ExWarehouse transfer = null;
            ExWarehouse deals = null;


            TaskVo taskVo = taskService.queryById(id);
            TaskBo taskBo = new TaskBo();
            BeanUtil.copyProperties(taskVo,taskBo);

            /**
             * 移交时，如果为移交上级库，默认设置为下发时选择的仓库
             */
            if(StringUtils.isNotEmpty(vo.getStoreId())){
                taskBo.setStoreId(vo.getStoreId());
            }

            /**
             * 判断是否跨级确认
             */
            SysDept confirmDept = deptService.selectDeptById(taskVo.getDeptId());

            TaskDtlBo dtlBo = new TaskDtlBo();
            dtlBo.setTaskId(id);
            dtlBo.setDelFlag("0");
            List<TaskDtlVo> dtls = taskDtlService.queryList(dtlBo);

            OrderVo orderVo = orderService.queryByTaskId(id);
            OrderBo orderBo = new OrderBo();
            orderBo.setDelFlag("0");
            if(ObjectUtil.isNotNull(orderVo)){
                BeanUtil.copyProperties(orderVo,orderBo);
            }
            List<OrderDtlVo> orderDtls = dtls.stream().map(item->{
                OrderDtlVo orderDtl = new OrderDtlVo();
                BeanUtil.copyProperties(item,orderDtl,"id");
                return orderDtl;
            }).collect(Collectors.toList());
            orderBo.setItems(orderDtls);

            ClientVo clientVo = clientService.queryByDeptId(taskBo.getDeptId());

            if(ObjectUtil.isNotNull(clientVo)){
                orderBo.setClientId(clientVo.getId());
                orderBo.setClientContacts(clientVo.getContacts());
                orderBo.setClientTel(clientVo.getTel());
                orderBo.setClientName(clientVo.getName());
            }

            switch (taskBo.getType()){
                case "0"://入库下发
                {
                    if(StringUtils.isEmpty(vo.getStoreId())){
                        throw new ServiceException("仓库信息获取异常，请联系管理员！");
                    }
                    store = storeService.queryById(vo.getStoreId());
                    if(ObjectUtil.isNull(store)){
                        throw new ServiceException("仓库不存在，请联系管理员！");
                    }
                    taskBo.setProjectPickTime(vo.getProjectPickTime());

                    WarehouseVo warehouseVo = warehouseService.queryByTaskId(id);
                    WarehouseBo warehouseBo = new WarehouseBo();
                    warehouseBo.setDelFlag("0");
                    List<WarehouseDtlVo> wdtls = dtls.stream().map(item->{
                        WarehouseDtlVo wdtl = new WarehouseDtlVo();
                        BeanUtil.copyProperties(item,wdtl,"id");
                        return wdtl;
                    }).collect(Collectors.toList());

                    warehouseBo.setItems(wdtls);

                    if(ObjectUtil.isNull(warehouseVo)){
                        BeanUtil.copyProperties(taskBo,warehouseBo,ignoreProperties);
                        warehouseBo.setWno(taskBo.getTaskNo());
                        warehouseBo.setTaskId(taskBo.getId());
                        warehouseBo.setFlag(taskBo.getDelivery());
                        warehouseBo.setIsFinish("0");//是否上架结束 0-待上架 1-已结束
                        warehouseBo.setIsValidate("0");//是否需要确认 0-无需确认 1-需确认

                        if(confirmDept.getLevel() == 1){//3-市级 2-区级 1-地方派出所/所队
                            warehouseBo.setIsValidate("1");
                        }

                        warehouseBo.setIsSign("0");//是否已签收 0-待签收 1-已签收
                        warehouseBo.setStoreId(vo.getStoreId());
                        warehouse = warehouseService.insertByBo(warehouseBo);
                    }else {
                        BeanUtil.copyProperties(warehouseVo,warehouseBo,updateIgnore);
                        warehouseBo.setStoreId(taskBo.getStoreId());
                        warehouseBo.setNums(taskBo.getNums());
                        warehouse = warehouseService.updateByBo(warehouseBo);
                    }
                    if(ObjectUtil.isNotNull(warehouse)){
                        objid = warehouse.getId();
                    }

                    /*********** 订单信息  ***********/
                    //设置寄件人
                    orderBo.setSendAddr(taskVo.getDeptName());
                    orderBo.setSendAddress(taskVo.getAddress());
                    orderBo.setSendTel(taskVo.getTel());
                    orderBo.setSendContacts(taskVo.getName());

                    if(ObjectUtil.isNotNull(clientVo)){
                        orderBo.setSendLat(clientVo.getLat());
                        orderBo.setSendLng(clientVo.getLng());
                    }

                    //设置收件人
                    orderBo.setTakeAddr(store.getName());
                    orderBo.setTakeAddress(store.getAddress());
                    orderBo.setTakeLng(store.getLng());
                    orderBo.setTakeLat(store.getLat());
                    orderBo.setTakeContacts(store.getNickName());
                    orderBo.setTakeTel(store.getPhonenumber());


                    //上架任务
//                    initPutTaskVoByWarehouse(warehouseBo);

                    break;
                }
                case "1"://出库下发
                {
                    if(taskBo.getCheckStatus().equals("0")){
                        throw new ServiceException("检查到下发的申请单中存在未审核申请单,请重新选择后下发");
                    }
                    else if(taskBo.getCheckStatus().equals("2")){
                        throw new ServiceException("检查到下发的申请单中存在审核未通过的申请单,请重新选择后下发");
                    }

                    store = storeService.queryById(taskBo.getStoreId());

                    ExWarehouseVo exWarehouseVo = exWarehouseService.queryByTaskId(id);
                    ExWarehouseBo exWarehouseBo = new ExWarehouseBo();
                    exWarehouseBo.setDelFlag("0");
                    List<ExWarehouseDtlVo> ewdtls = dtls.stream().map(item->{
                        ExWarehouseDtlVo ewdtl = new ExWarehouseDtlVo();
                        BeanUtil.copyProperties(item,ewdtl,"id");
                        return ewdtl;
                    }).collect(Collectors.toList());

                    exWarehouseBo.setItems(ewdtls);

                    if(ObjectUtil.isNull(exWarehouseVo)){
                        BeanUtil.copyProperties(taskBo,exWarehouseBo,ignoreProperties);
                        exWarehouseBo.setExno(taskBo.getTaskNo());
                        exWarehouseBo.setTaskId(taskBo.getId());
                        exWarehouseBo.setFlag(taskBo.getDelivery());
                        exWarehouseBo.setIsFinish("0");//是否上架结束 0-待上架 1-已结束
                        exWarehouseBo.setIsValidate("0");//是否需要确认 0-无需确认 1-需确认

                        if(confirmDept.getLevel() == 1){//3-市级 2-区级 1-地方派出所/所队
                            exWarehouseBo.setIsValidate("1");
                        }

                        exWarehouseBo.setIsSign("0");//是否已签收 0-待签收 1-已签收
                        exWarehouseBo.setStoreId(vo.getStoreId());
                        exWarehouse = exWarehouseService.insertByBo(exWarehouseBo);
                    }else {
                        BeanUtil.copyProperties(exWarehouseVo,exWarehouseBo,updateIgnore);
                        exWarehouse.setStoreId(taskBo.getStoreId());
                        exWarehouse.setNums(taskBo.getNums());
                        exWarehouse = exWarehouseService.updateByBo(exWarehouseBo);
                    }
                    if(ObjectUtil.isNotNull(exWarehouse)){
                        objid = exWarehouse.getId();
                    }

                    /*********** 订单信息  ***********/
                    //设置寄件人
                    orderBo.setSendAddr(store.getName());
                    orderBo.setSendAddress(store.getAddress());
                    orderBo.setSendLng(store.getLng());
                    orderBo.setSendLat(store.getLat());
                    orderBo.setSendContacts(store.getNickName());
                    orderBo.setSendTel(store.getPhonenumber());

                    //设置收件人
                    orderBo.setTakeAddr(taskVo.getTakeDeptName());
                    orderBo.setTakeAddress(taskVo.getTakeAddress());
                    orderBo.setTakeLng(taskVo.getTakeLng());
                    orderBo.setTakeLat(taskVo.getTakeLat());
                    orderBo.setTakeContacts(taskVo.getTakeContacts());
                    orderBo.setTakeTel(taskVo.getTakeTel());
                    taskBo.setSigneeName(vo.getSigneeName());

                    //挑拣任务
                    initPick(exWarehouseBo);

                    break;
                }
                case "2"://处置下发
                {
                    store = storeService.queryById(taskBo.getStoreId());

                    ExWarehouseVo dealVo = exWarehouseService.queryByTaskId(id);
                    ExWarehouseBo dealBo = new ExWarehouseBo();
                    dealBo.setDelFlag("0");
                    List<ExWarehouseDtlVo> ddtls = dtls.stream().map(item->{
                        ExWarehouseDtlVo ddtl = new ExWarehouseDtlVo();
                        BeanUtil.copyProperties(item,ddtl,"id");
                        return ddtl;
                    }).collect(Collectors.toList());

                    dealBo.setItems(ddtls);

                    if(ObjectUtil.isNull(dealVo)){
                        BeanUtil.copyProperties(taskBo,dealBo,ignoreProperties);
                        dealBo.setExno(taskBo.getTaskNo());
                        dealBo.setTaskId(taskBo.getId());
                        dealBo.setFlag(taskBo.getDelivery());
                        dealBo.setIsFinish("0");//是否上架结束 0-待挑拣 1-已挑拣
                        dealBo.setIsValidate("0");//是否需要确认 0-无需确认 1-需确认
                        dealBo.setIsSign("0");//是否已签收 0-待签收 1-已签收
                        dealBo.setStoreId(store.getId());
                        dealBo.setReturnStatus("0");
                        dealBo.setContacts(taskBo.getName());
                        deals = exWarehouseService.insertByBo(dealBo);
                    }else {
                        BeanUtil.copyProperties(dealVo,dealBo,updateIgnore);
                        dealBo.setNums(taskBo.getNums());
                        dealBo.setStoreId(taskBo.getStoreId());
                        deals = exWarehouseService.updateByBo(dealBo);
                    }
                    if(ObjectUtil.isNotNull(deals)){
                        objid = deals.getId();
                    }

                    /*********** 订单信息  ***********/
                    //设置寄件人
                    orderBo.setSendAddr(store.getName());
                    orderBo.setSendAddress(store.getAddress());
                    orderBo.setSendLng(store.getLng());
                    orderBo.setSendLat(store.getLat());
                    orderBo.setSendContacts(store.getNickName());
                    orderBo.setSendTel(store.getPhonenumber());

                    //设置收件人
//                    orderBo.setTakeAddr(taskVo.getTakeDeptName());
//                    orderBo.setTakeAddress(taskVo.getTakeAddress());
//                    orderBo.setTakeLng(taskVo.getTakeLng());
//                    orderBo.setTakeLat(taskVo.getTakeLat());
//                    orderBo.setTakeContacts(taskVo.getTakeContacts());
//                    orderBo.setTakeTel(taskVo.getTakeTel());

                    orderBo.setTakeAddr(taskVo.getDeptName());
                    orderBo.setTakeAddress(taskVo.getAddress());
                    orderBo.setTakeTel(taskVo.getTel());
                    orderBo.setTakeContacts(taskVo.getName());
                    taskBo.setSigneeName(vo.getSigneeName());

                    if(ObjectUtil.isNotNull(clientVo)){
                        orderBo.setTakeLat(clientVo.getLat());
                        orderBo.setTakeLng(clientVo.getLng());
                    }

                    //挑拣任务
                    initPick(dealBo);

                    break;
                }
                case "3"://调用下发
                {
                    store = storeService.queryById(taskBo.getStoreId());

//                    if(taskBo.getCheckStatus().equals("0")){
//                        throw new ServiceException("检查到下发的申请单中存在未审核申请单,请重新选择后下发");
//                    }
//                    else if(taskBo.getCheckStatus().equals("2")){
//                        throw new ServiceException("检查到下发的申请单中存在审核未通过的申请单,请重新选择后下发");
//                    }
                    ExWarehouseVo transferVo = exWarehouseService.queryByTaskId(id);
                    ExWarehouseBo transferBo = new ExWarehouseBo();
                    transferBo.setDelFlag("0");
                    List<ExWarehouseDtlVo> tdtls = dtls.stream().map(item->{
                        ExWarehouseDtlVo tdtl = new ExWarehouseDtlVo();
                        BeanUtil.copyProperties(item,tdtl,"id");
                        return tdtl;
                    }).collect(Collectors.toList());

                    transferBo.setItems(tdtls);

                    if(ObjectUtil.isNull(transferVo)){
                        BeanUtil.copyProperties(taskBo,transferBo,ignoreProperties);
                        transferBo.setExno(taskBo.getTaskNo());
                        transferBo.setTaskId(taskBo.getId());
                        transferBo.setFlag(taskBo.getDelivery());
                        transferBo.setIsFinish("0");//是否上架结束 0-待上架 1-已结束
                        transferBo.setIsValidate("0");//是否需要确认 0-无需确认 1-需确认
                        transferBo.setIsSign("0");//是否已签收 0-待签收 1-已签收
                        transferBo.setStoreId(store.getId());
                        transferBo.setContacts(taskBo.getName());
                        transfer = exWarehouseService.insertByBo(transferBo);
                    }else {
                        BeanUtil.copyProperties(transferVo,transferBo,updateIgnore);
                        transferBo.setNums(taskBo.getNums());
                        transferBo.setStoreId(taskBo.getStoreId());
                        transfer = exWarehouseService.updateByBo(transferBo);
                    }
                    if(ObjectUtil.isNotNull(transfer)){
                        objid = transfer.getId();
                    }

                    /*********** 订单信息  ***********/
                    //设置寄件人
                    orderBo.setSendAddr(store.getName());
                    orderBo.setSendAddress(store.getAddress());
                    orderBo.setSendLng(store.getLng());
                    orderBo.setSendLat(store.getLat());
                    orderBo.setSendContacts(store.getNickName());
                    orderBo.setSendTel(store.getPhonenumber());


                    //设置收件人
//                    orderBo.setTakeAddr(taskVo.getTakeDeptName());
//                    orderBo.setTakeAddress(taskVo.getTakeAddress());
//                    orderBo.setTakeLng(taskVo.getTakeLng());
//                    orderBo.setTakeLat(taskVo.getTakeLat());
//                    orderBo.setTakeContacts(taskVo.getTakeContacts());
//                    orderBo.setTakeTel(taskVo.getTakeTel());

                    orderBo.setTakeAddr(taskVo.getDeptName());
                    orderBo.setTakeAddress(taskVo.getAddress());
                    orderBo.setTakeTel(taskVo.getTel());
                    orderBo.setTakeContacts(taskVo.getName());
                    taskBo.setSigneeName(vo.getSigneeName());

                    if(ObjectUtil.isNotNull(clientVo)){
                        orderBo.setTakeLat(clientVo.getLat());
                        orderBo.setTakeLng(clientVo.getLng());
                    }

                    //挑拣任务
                    initPick(transferBo);
                    break;

                }
                default:
                    break;
            }

            boolean flag = true;
            //处置，并且授权
            if(taskBo.getType().equals("2") && taskBo.getIsTrailer().equals("1")){
                flag = false;
            }

            if(taskBo.getDelivery().equals("0") && flag){
                OrderVo enty = null;
                OrderBo entyBo = new OrderBo();
                if(StringUtils.isEmpty(orderBo.getId())){
                    orderBo.setNums(taskBo.getNums());
                    orderBo.setTaskId(taskBo.getId());
                    orderBo.setDeptId(taskBo.getDeptId());
                    orderBo.setObjId(objid);
                    orderBo.setOrderNo(taskBo.getTaskNo());
                    orderBo.setStatus("0");
                    //物品单 状态设为待取件
                    if(taskBo.getBuss().equals("0")){
                        orderBo.setStatus("1");//待取件
                    }
                    orderBo.setIsStaging("0");
                    orderBo.setSourceType("0");
                    orderBo.setBuss(taskBo.getBuss());
                    orderBo.setType(taskBo.getType());
                    orderBo.setDeliveryType(taskBo.getDelivery());
                    //设置调度员
                    orderBo.setDispatcherId(LoginHelper.getUserId());
                    orderBo.setCarrierDeptId(vo.getCarrierDeptId());
                    enty = orderService.insertByBo(orderBo);
                }else {
                    enty = orderService.updateByBo(orderBo);
                }

                CarrierVo carrierVo = carrierService.selectCarrierByDeptId(vo.getCarrierDeptId());
                if(carrierVo != null && carrierVo.getBingUserId() != null){
                    //下发给指定承运商
                    List<String> toUsers = new ArrayList<>();
                    toUsers.add(carrierVo.getBingUserId().toString());
                    commonService.sendSysNotice("1",toUsers,taskBo.getDeptId(),"取件提醒","有一条指派给您的订单，请及时跟进！","{\"page\":\"/pagesOMS/staging/index\"}");
                }


                if(StringUtils.isNotEmpty(enty.getId())){
                    BeanUtil.copyProperties(enty,entyBo);

                    /**
                     * 车辆流转日志
                     * 0-接收 1-接车人APP联系客户 2-出发 3-到达接车地 4-运输过程 5-到达目的地 6-卸车 7-完工
                     */
                    if(enty.getBuss().equals("1")){
//                        commonService.saveOrderLog(entyBo,"0");
                    }

                    WaybillBo wentyBo = new WaybillBo();
                    WaybillVo wenty = null;

                    //存在车辆以及配送员时，创建运单
//                    if(StringUtils.isNotEmpty(vo.getCarId()) && vo.getPickupId() != null){
//                    if(vo.getPickupId() != null){
                        CarVo car = null;
                        if(StringUtils.isNotEmpty(vo.getCarId())){
                            entyBo.setCarId(vo.getCarId());
                            car = carService.queryById(vo.getCarId());
                            entyBo.setCarNumber(car.getCarNumber());
                        }
                        if(vo.getPickupId() != null){
                            entyBo.setPickupId(vo.getPickupId());
                            entyBo.setStatus("1");

                        }
                        entyBo.setDispatchId(vo.getDispatchId() != null ? vo.getDispatchId():vo.getPickupId());
                        entyBo.setCarStatus("0");
                        if(vo.getCarrierDeptId() != null){
                            entyBo.setCarrierDeptId(vo.getCarrierDeptId());
                        }
                        orderService.updateByOrder(entyBo);

                        //创建运单
                        WaybillVo waybillVo = waybillService.queryByOrderId(enty.getId());
                        WaybillBo waybillBo = new WaybillBo();
                        waybillBo.setDelFlag("0");
                        if(ObjectUtil.isNotNull(waybillVo)){
                            BeanUtil.copyProperties(waybillVo,waybillBo);
                            waybillBo.setNums(enty.getNums().intValue());
                        }

                    if(StringUtils.isNotEmpty(vo.getSigneeName())){
                        waybillBo.setSigner(vo.getSigneeName());
                    }
                        waybillBo.setLogContent("派单");
                        waybillBo.setLogType(PropertyLogType.DISPATCH.getCode());

                        List<WaybillDtlVo> waybillDtls = dtls.stream().map(item->{
                            WaybillDtlVo waybillDtl = new WaybillDtlVo();
                            BeanUtil.copyProperties(item,waybillDtl,"id");
                            return waybillDtl;
                        }).collect(Collectors.toList());
                        waybillBo.setItems(waybillDtls);

                        if(StringUtils.isEmpty(waybillBo.getId())){
                            waybillBo.setOrderId(enty.getId());
                            //车牌号
                            if(car != null){
                                waybillBo.setCarNumber(car.getCarNumber());
                                waybillBo.setCarId(car.getId());
                            }
                            //调度员
                            waybillBo.setDispatcherId(enty.getDispatcherId());
                            waybillBo.setDispatcher(userService.selectUserById(enty.getDispatcherId()).getNickName());
                            //设置派单时间
                            waybillBo.setDispatchTime(new Date());
                            //设置接单时间
                            waybillBo.setTakeBillTime(new Date());
                            waybillBo.setBuss(enty.getBuss());
                            //设置为待发车
                            waybillBo.setStatus("0");
                            //物品单 状态设为待发车
                            if(taskBo.getBuss().equals("0")){
                                waybillBo.setStatus("2");//待发车
                            }
                            //司机
                            if(vo.getPickupId() != null){
                                waybillBo.setDriverName(userService.selectUserById(vo.getPickupId()).getNickName());
                                waybillBo.setStatus("2");
                            }
                            //承运商
                            waybillBo.setNums(orderBo.getNums().intValue());
                            CarrierBo carrierBo = new CarrierBo();
                            carrierBo.setDeptId(vo.getCarrierDeptId());
                            waybillBo.setCarrierId(carrierService.queryList(carrierBo).get(0).getId());

                            wenty = waybillService.insertByBo(waybillBo);
                        }else {
                            waybillBo.setNums(enty.getNums().intValue());
                            wenty = waybillService.dispatchWaybillByBo(waybillBo);
                        }
//                        if(ObjectUtil.isNotNull(wenty) && StringUtils.isNotEmpty(wenty.getId())){
//                            BeanUtil.copyProperties(wenty,wentyBo);
//                            //运单日志
//                            commonService.saveWaybillLog(wentyBo,"0");
//                            if(wenty.getBuss().equals("1")){//车辆单，新增一条派单日志
//                                commonService.saveWaybillLog(wentyBo,"1");//派单
//                            }
//                        }

                        //下发给指定取/派件员
                        if(vo.getPickupId() != null){
                            List<String> toUsers = new ArrayList<>();
                            toUsers.add(vo.getPickupId().toString());
                            commonService.sendSysNotice("1",toUsers,taskBo.getDeptId(),"取件提醒","有一条指派给您的订单，请及时处理！","{\"page\":\"/pagesOMS/staging/index\"}");
                        }

//                    }
                }

                //订单推送
                commonService.orderPush(enty.getId());
            }

            taskBo.setSendStatus("1");
            taskBo.setSendReStatus("1");
//            taskBo.setAction("sendsTask");//下发操作
//            taskService.updateTaskBo(taskBo);
            if(taskBo.getDelivery().equals("0")){
                taskBo.setDispatcherId(LoginHelper.getUserId());
            }
            taskService.updateTaskEnty(taskBo);

            if(ObjectUtil.isNotNull(store)){
                //下发给仓库管理员
                List<String> toUsers = new ArrayList<>();
                toUsers.add(store.getUserId().toString());
                String contentInfo = "您有1条"+taskBo.getDealTypeName()+"的申请下发，请及时跟进！";
                commonService.sendSysNotice("1",toUsers,taskBo.getDeptId(),"申请下发提醒",contentInfo,"{\"page\":\"/pagesOMS/staging/index\"}");
            }

            //仓库日志
            commonService.saveStoreLog(taskBo);


            //操作日志
            commonService.saveOperatorLog(taskBo.getId(),"oms","下发");
        }
    }

    public void initPutTaskVoByWarehouse(WarehouseBo warehouse) {
        PutTaskVo vo = putTaskMapper.queryPutTaskVoByWarehouseID(warehouse.getId());
        if(vo != null){
            PutTask update = BeanUtil.toBean(vo, PutTask.class);
            update.setStatus("0");
            List<PutDtl> dtls = new ArrayList<>();
            Long nums = 0L;
            putDtlMapper.deleteByPutId(update.getId());
            if(warehouse.getItems() != null && warehouse.getItems().size() > 0){
                for(WarehouseDtlVo item : warehouse.getItems()){
                    PutDtl dtl = new PutDtl();
                    dtl.setId(IdUtil.simpleUUID());
                    dtl.setTaskId(update.getId());
                    dtl.setDelFlag("0");
                    dtl.setPno(item.getPno());
                    dtl.setName(item.getName());
                    dtl.setStoreId(warehouse.getStoreId());

                    InventoryVo inventory = inventoryMapper.selectInventoryVoByPno(item.getPno());
                    if(inventory != null){
                        dtl.setAreaId(inventory.getAreaId());
                        dtl.setLocatorId(inventory.getLocatorId());
                    }

                    dtl.setStatus("0");
                    dtl.setNums(item.getNums() == null ? 1L : item.getNums());
                    dtl.setPrintFlag(0);
                    dtls.add(dtl);
                    nums += dtl.getNums();
                }
            }
            if(dtls != null && dtls.size() > 0){
                putDtlMapper.insertBatch(dtls);
            }
            update.setNums(nums);
            putTaskMapper.updateById(update);
        }else{
            PutTask add = new PutTask();
            add.setId(IdUtil.simpleUUID());
            add.setDelFlag("0");
            add.setWid(warehouse.getId());
            add.setDeptId(warehouse.getDeptId());
            add.setTaskNo(warehouse.getWno());
            add.setStatus("0");
            List<PutDtl> dtls = new ArrayList<>();
            Long nums = 0L;

            if(warehouse.getItems() != null && warehouse.getItems().size() > 0){
                for(WarehouseDtlVo item : warehouse.getItems()){
                    PutDtl dtl = new PutDtl();
                    dtl.setId(IdUtil.simpleUUID());
                    dtl.setTaskId(add.getId());
                    dtl.setDelFlag("0");
                    dtl.setPno(item.getPno());
                    dtl.setName(item.getName());
                    dtl.setStoreId(warehouse.getStoreId());

                    InventoryVo inventory = inventoryMapper.selectInventoryVoByPno(item.getPno());
                    if(inventory != null){
                        dtl.setAreaId(inventory.getAreaId());
                        dtl.setLocatorId(inventory.getLocatorId());
                    }

                    dtl.setStatus("0");
                    dtl.setNums(item.getNums() == null ? 1L : item.getNums());
                    dtl.setPrintFlag(0);
                    dtls.add(dtl);
                    nums += dtl.getNums();
                }
            }
            if(dtls != null && dtls.size() > 0){
                putDtlMapper.insertBatch(dtls);
            }
            add.setNums(nums);
            putTaskMapper.insert(add);
        }
    }

    public void initPick(ExWarehouseBo exWarehouseBo) {
        PickVo vo = pickMapper.queryPickVoByExWarehouseID(exWarehouseBo.getId());
        if(vo == null){
            Pick add = new Pick();
            add.setWid(exWarehouseBo.getId());
            add.setStoreId(exWarehouseBo.getStoreId());
            add.setDeptId(LoginHelper.getDeptId());
            add.setPickNo(exWarehouseBo.getTaskNo());
            add.setStatus("0");
            add.setDelFlag("0");
            add.setId(IdUtil.simpleUUID());
            if(exWarehouseBo.getType().equals("1")){
                add.setPickType("0");
            }
            if(exWarehouseBo.getType().equals("3")){
                add.setPickType("1");
            }
            if(exWarehouseBo.getType().equals("2")){
                add.setPickType("2");
            }

            List<PickDtl> dtls = exWarehouseBo.getItems().stream().map(item->{
                PickDtl dtl = new PickDtl();
                dtl.setPno(item.getPno());
                dtl.setName(item.getName());
                dtl.setNums(item.getNums());

                InventoryVo inventory = inventoryMapper.selectInventoryVoByPno(dtl.getPno());

                dtl.setId(IdUtil.simpleUUID());
                dtl.setDelFlag("0");
                dtl.setStatus("0");
                dtl.setLocatorId(inventory.getLocatorId());
                dtl.setStoreId(add.getStoreId());
                dtl.setAreaId(inventory.getAreaId());
                dtl.setPickId(add.getId());
                return dtl;
            }).collect(Collectors.toList());

            //设置挑拣总数
            Long nums = dtls.stream().mapToLong(item-> item.getNums()).sum();
            add.setNums(nums);

            pickMapper.insert(add);
            pickDtlMapper.insertBatch(dtls);

        }else {
            Pick update = new Pick();
            update.setId(vo.getId());
            update.setStatus("0");
            List<PickDtl> dtls = exWarehouseBo.getItems().stream().map(item->{
                PickDtl dtl = new PickDtl();
                dtl.setPno(item.getPno());
                dtl.setName(item.getName());
                dtl.setNums(item.getNums());

                InventoryVo inventory = inventoryMapper.selectInventoryVoByPno(dtl.getPno());

                dtl.setId(IdUtil.simpleUUID());
                dtl.setDelFlag("0");
                dtl.setStatus("0");
                dtl.setLocatorId(inventory.getLocatorId());
                dtl.setStoreId(vo.getStoreId());
                dtl.setAreaId(inventory.getAreaId());
                dtl.setPickId(vo.getId());
                return dtl;
            }).collect(Collectors.toList());

            //设置挑拣总数
            Long nums = dtls.stream().mapToLong(item-> item.getNums()).sum();
            update.setNums(nums);

            pickMapper.updateById(update);
            pickDtlMapper.deletePickDtlByPickId(update.getId());
            pickDtlMapper.insertBatch(dtls);

        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelSendTask(TaskVo task) {
        Warehouse warehouse = null;
        ExWarehouse exWarehouse = null;

        switch (task.getType()){
            case "0":
                warehouse = warehouseMapper.selectOne(new LambdaQueryWrapper<Warehouse>().eq(Warehouse::getTaskId,task.getId()));
                break;
            case "1":
                exWarehouse = exWarehouseMapper.selectOne(new LambdaQueryWrapper<ExWarehouse>().eq(ExWarehouse::getTaskId,task.getId()));
                break;
            case "2":
                exWarehouse = exWarehouseMapper.selectOne(new LambdaQueryWrapper<ExWarehouse>().eq(ExWarehouse::getTaskId,task.getId()));
                break;
            case "3":
                exWarehouse = exWarehouseMapper.selectOne(new LambdaQueryWrapper<ExWarehouse>().eq(ExWarehouse::getTaskId,task.getId()));
                break;
        }
        /**
         * 撤销下发信息
         */
        if(ObjectUtil.isNotNull(warehouse) && StringUtils.isNotEmpty(warehouse.getId())){
            warehouseMapper.removeWarehouse(warehouse.getId());

            List<WarehouseDtl> items = warehouseDtlMapper.selectList(new LambdaQueryWrapper<WarehouseDtl>().eq(WarehouseDtl::getWid,warehouse.getId()));

            if(items != null && items.size() > 0){
                warehouseDtlMapper.removeWarehouseDtlBatch(items);
            }
        }

        if(ObjectUtil.isNotNull(exWarehouse) && StringUtils.isNotEmpty(exWarehouse.getId())){
            exWarehouseMapper.removeExWarehouse(exWarehouse.getId());

            List<ExWarehouseDtl> items = exWarehouseDtlMapper.selectList(new LambdaQueryWrapper<ExWarehouseDtl>().eq(ExWarehouseDtl::getWid,exWarehouse.getId()));

            if(items != null && items.size() > 0){
                exWarehouseDtlMapper.removeExWarehouseDtlBatch(items);
            }
        }

        Order order = orderMapper.selectOne(new LambdaQueryWrapper<Order>().eq(Order::getTaskId,task.getId()));

        if(ObjectUtil.isNotNull(order) && StringUtils.isNotEmpty(order.getId())){
            orderMapper.removeOrder(order.getId());

            List<OrderDtl> items = orderDtlMapper.selectList(new LambdaQueryWrapper<OrderDtl>().eq(OrderDtl::getOrderId,order.getId()));

            if(items != null && items.size() > 0){
                orderDtlMapper.removeOrderDtlBatch(items);
            }

            List<OrderLog> logs = orderLogMapper.selectList(new LambdaQueryWrapper<OrderLog>().eq(OrderLog::getOrderId,order.getId()));
            if(logs != null && logs.size() > 0){
                orderLogMapper.removeOrderLogBatch(logs);
            }

            /**
             * 已派单运单删除
             */
            Waybill waybill = waybillMapper.selectOne(new LambdaQueryWrapper<Waybill>().eq(Waybill::getOrderId,order.getId()));

            if(ObjectUtil.isNotNull(waybill) && StringUtils.isNotEmpty(waybill.getId())){
                waybillMapper.removeWayBill(waybill.getId());

                List<WaybillDtl> wDtls = waybillDtlMapper.selectList(new LambdaQueryWrapper<WaybillDtl>().eq(WaybillDtl::getWaybillId,waybill.getId()));

                if(wDtls != null && wDtls.size() > 0){
                    waybillDtlMapper.removeWaybillDtlBatch(wDtls);
                }

                List<WaybillLog> wLogs = waybillLogMapper.selectList(new LambdaQueryWrapper<WaybillLog>().eq(WaybillLog::getTrackId,waybill.getId()));

                if(wLogs != null && wLogs.size() > 0){
                    waybillLogMapper.removeWaybillLogBatch(wLogs);
                }
            }
        }
    }

    @Override
    public List<Map<String, Object>> indexSchedule() {
        List<Map<String, Object>> results = new ArrayList<>();

        /**
         * 获取待下发编号信息
         */
        TaskBo taskBo = new TaskBo();
        taskBo.setDelFlag("0");
        taskBo.setSendStatus("0");
        List<TaskVo> taskVoList = taskService.queryList(taskBo);

        if(taskVoList != null && taskVoList.size() > 0){
            taskVoList.stream().forEach(taskVo->{
                Map<String, Object> map = new HashMap<>();
                map.put("id",taskVo.getId());
                map.put("textNo",taskVo.getTaskNo());
                map.put("deptName",taskVo.getDeptName());
                map.put("type",taskVo.getType());
                map.put("delivery",taskVo.getDelivery());
                map.put("createTime",taskVo.getCreateTime());
                map.put("storeName",taskVo.getStoreName());
                map.put("checkStatus",taskVo.getCheckStatus());
                results.add(map);

            });
        }

        ViewingBo viewingBo = new ViewingBo();
        viewingBo.setCheckStatus("0");
        List<ViewingVo> viewingVos = viewingMapper.selectViewingList(viewingBo);
        if(viewingVos != null && viewingVos.size() > 0){
            viewingVos.stream().forEach(viewingVo->{
                Map<String, Object> map = new HashMap<>();
                map.put("id",viewingVo.getId());
                map.put("textNo",viewingVo.getViewingNo());
                map.put("deptName",viewingVo.getDeptName());
                map.put("createTime",viewingVo.getCreateTime());
                map.put("storeName",viewingVo.getStoreName());
                map.put("checkStatus",viewingVo.getCheckStatus());
                if(viewingVo.getType().equals("0")){
                    map.put("type","4");
                    results.add(map);
                }else {
                    map.put("type","5");
                    results.add(map);
                }
            });
        }

        StagingBo stagingBo = new StagingBo();
        stagingBo.setWarnShow("1");
        List<StagingVo> stagingVos = stagingMapper.selectStagingList(stagingBo);
        if(stagingVos != null && stagingVos.size() > 0){
            stagingVos.stream().forEach(stagingVo->{
                Map<String, Object> map = new HashMap<>();
                map.put("id",stagingVo.getId());
                map.put("textNo",stagingVo.getPno());
                map.put("deptName",stagingVo.getOfficeName());
                map.put("type","6");
                map.put("createTime",stagingVo.getCreateTime());
//                map.put("status",s);
                results.add(map);
            });
        }
        TaskDtlBo dtlBo = new TaskDtlBo();
        dtlBo.setIsReturn("1");
        List<TaskDtlVo> taskDtlVos = taskDtlService.queryList(dtlBo);
        if(taskDtlVos != null && taskDtlVos.size() > 0){
            taskDtlVos.stream().forEach(taskDtlVo->{
                Map<String, Object> map = new HashMap<>();
                map.put("id",taskDtlVo.getTaskId());
                map.put("textNo",taskDtlVo.getTaskNo());
                map.put("deptName",taskDtlVo.getDeptName());
                map.put("type","7");
                results.add(map);
            });
        }
        return results;
    }

    @Override
    public Map<String, Object> indexScheduleV2() {
        Map<String, Object> data = new HashMap<>();
        /**
         * 待办事项
         * 0-入库 1-出库 2-处置 3-调用
         */
        TaskBo rbo = new TaskBo();
        rbo.setType("0");
        rbo.setSendStatus("0");//查询待下发数据
        Long inums = taskService.selectCountTask(rbo);
        data.put("inums",inums);

        TaskBo ebo = new TaskBo();
        ebo.setType("1");
        ebo.setIsSendWithCheck(true);
        Long onums = taskService.selectCountTask(ebo);
        data.put("onums",onums);


        TaskBo cbo = new TaskBo();
        cbo.setType("2");
        cbo.setIsDealsWithCheck(true);
        Long deals = taskService.selectCountTask(cbo);
        data.put("deals",deals);

        TaskBo tbo = new TaskBo();
        tbo.setType("3");
        tbo.setIsSendWithCheck(true);
        Long tnums = taskService.selectCountTask(tbo);
        data.put("tnums",tnums);

        /**
         * 移交预警
         */
        StagingBo stagingBo = new StagingBo();
        stagingBo.setWarnShow("1");
        List<StagingVo> stagingVos = stagingMapper.selectStagingList(stagingBo);
        data.put("snums",stagingVos.size());

        /**
         * 阅证申请
         */
        ViewingBo viewingBo = new ViewingBo();
        viewingBo.setCheckStatus("0");
        List<ViewingVo> viewingVos = viewingMapper.selectViewingList(viewingBo);
        data.put("vnums",viewingVos.size());

        /**
         * 归还预警
         */
        TaskDtlBo dtlBo = new TaskDtlBo();
        dtlBo.setIsReturn("1");
        List<TaskDtlVo> taskDtlVos = taskDtlService.queryList(dtlBo);
        data.put("rnums",taskDtlVos.size());

        /**
         * 处置登记预警
         */
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(1);
        pageQuery.setPageSize(Integer.MAX_VALUE);
        DealDtlBo dbo = new DealDtlBo();
        Page<DealDtlVo> result = dealDtlMapper.warnDealDtl(pageQuery.build(), dbo);
        data.put("cnums",result.getTotal());
        return data;
    }

//    @Override
//    public void sendDealTask(Task task) {
//        //忽略参数
//        String[] ignoreProperties = {"id","createBy","createTime","updateBy","updateTime"};
//        TaskDtlBo dtlBo = new TaskDtlBo();
//        dtlBo.setTaskId(task.getId());
//        dtlBo.setDelFlag("0");
//        List<TaskDtlVo> dtls = taskDtlService.queryList(dtlBo);
//
//        dealMapper.deleteByTaskId(task.getId());
//        dealDtlMapper.deleteByTaskId(task.getId());
//        /**
//         * 处置明细
//         */
//        for(TaskDtlVo dtl : dtls){
//            Deal deal = new Deal();
//            deal.setId(IdUtil.simpleUUID());
//            deal.setStatus("1");
//            deal.setDelFlag("0");
//            deal.setSource("0");
//            deal.setIsAck("0");
//            deal.setIsFinish("1");
//            deal.setTaskId(task.getId());
//            deal.setNums(task.getNums());
//            deal.setDealNo(dtl.getPno());
//            deal.setDealType(task.getDealType());
//            deal.setStoreId(task.getStoreId());
//            deal.setDeptId(task.getDeptId());
//            deal.setIsCheck("1");
//            deal.setIsSign("1");
//            deal.setIsRegister("0");
//            dealMapper.insert(deal);
//
//            DealDtl dealDtl = new DealDtl();
//            dealDtl.setId(IdUtil.simpleUUID());
//            dealDtl.setDelFlag("0");
//            dealDtl.setStatus("1");
//            dealDtl.setDealId(deal.getId());
//            dealDtl.setStoreId(dtl.getStoreId());
//            dealDtl.setPno(dtl.getPno());
//            dealDtl.setName(dtl.getName());
//            dealDtl.setNums(dtl.getNums());
//            dealDtl.setDealType(deal.getDealType());
//            dealDtlMapper.insert(dealDtl);
//        }
//
//
//        /**
//         * 下发状态
//         */
//        TaskBo updatebo = new TaskBo();
//        BeanUtil.copyProperties(task,updatebo);
//        updatebo.setStatus("1");
//        updatebo.setSendStatus("1");
//        updatebo.setSendReStatus("1");
//        taskService.updateTaskEnty(updatebo);
//
//        commonService.saveOperatorLog(task.getId(),"oms","下发");
//    }
}
